package com.restfinder.rate.dao;


import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.restfinder.common.dao.StandardDAO;
import com.restfinder.rate.model.Rate;
import com.restfinder.rate.model.RateCategory;
import com.restfinder.restaurant.model.Restaurant;
import com.restfinder.user.model.User;

@Repository
public class DatabaseRateRepository extends StandardDAO<Rate> implements RateRepository {

	private static final long serialVersionUID = 1L;

	@Override
	public Class getEntityClass() {
		return Rate.class;
	}
	
	public Rate getByUserAndRestaurant(User user, Restaurant restaurant){
		Query query = this.sessionFactory.getCurrentSession().createQuery("from Rate r where r.pk.user.id=:user_id and r.pk.restaurant.id=:restaurant_id").setLong("user_id", user.getId()).setLong("restaurant_id", restaurant.getId());
		Rate rate = (Rate) query.uniqueResult();
		return rate;
	}

	public double getAverage(Restaurant restaurant) {
		return 5.654;	//TODO
	}
	
	public double getAverage(Restaurant restaurant, RateCategory category){
		String property = category.getCategory();
		Query query = this.sessionFactory.getCurrentSession().createQuery("SELECT avg("+property+") FROM Rate r where r.pk.restaurant.id=:restaurant_id").setLong("restaurant_id", restaurant.getId());
		return (Double) query.list().get(0);
	}

}
